
/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */

HHJsLib.register({
    init: function() {
        this.bindShopIdChange();
        this.loadGoodsListAndExpList($('#shop_id').val());
         //包邮
         this.bindBtnSubBaoYou('a.btn-sub-bao-you');
         this.bindBtnAddBaoYou();
         this.bindBtnAddBaoYouAddress('a.btn-bao-you-add-address');
         //确认选择区域
         this.bindBtnSelectAddressSure();
         this.bindHasExpressChange();
    },
    bindHasExpressChange: function() {
        $('#has_express').change(function() {
            var id  = $(this).val();
            if(2 != id) {
                $('#tpl-baoyou-data-box').hide();
            } else {
                $('#tpl-baoyou-data-box').show();
            }
        });
    },
    bindBtnAddBaoYou: function() {
         var tpl    = $('#bao-you-item-tpl').html();
         var self   = this;
         $('#btn-add-bao-you').click(function() {
             var id = (new Date()).getTime();
             var trHtml     = tpl.replace(/{id}/g, id)
             .replace(/{express}/g, $('#express-list-tpl').html());
             $('#bao-you-list-box').append(trHtml);
             self.bindBtnSubBaoYou('#btn-sub-bao-you-' + id);
             self.bindBtnAddBaoYouAddress('#btn-bao-you-add-address-' + id);
         });
     },
     bindBtnAddBaoYouAddress: function(dom) {
        var self   = this;
        $(dom).click(function() {
             var id         = $(this).attr('data-id');
             var isLoaded   = $('#address-data-box').attr('data-loaded');
             $('#btn-select-address-sure')
             .attr('data-target', '#bao-you-address-box-' + id)
             .attr('data-field', '#bao-you-address-path-' + id);
             $('#select-address-modal').modal('show');
             if(1 == isLoaded) {
                 self.loadSelectAddressData();
                 return;
             }
             this.zTreeObj.checkAllNodes(false);
         });
     },
     setAllExpressList: function(optHtml) {
         $('select.express-list').each(function() {
             var $this  = $(this);
             $this.html(optHtml);
             HHJsLib.autoSelect($this);
         });
     },
     bindBtnSubBaoYou: function(dom) {
         $(dom).click(function() {
             var id     = $(this).attr('data-id');
             var itemId = $('#by-add-id-' + id).val();
             $('#bao-you-box-' + id).fadeOut('fast', function() {
                 $(this).remove();
             });
             if(!itemId) {
                 return;
             }
             $.getJSON(
                queryUrl + 'admin/goodsbydetail/adel',
                {id: itemId},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                }
             );
         });
     },
     bindBtnSelectAddressSure: function() {
         var self   = this;
         $('#btn-select-address-sure').click(function() {
             var target = $(this).attr('data-target');
             var field  = $(this).attr('data-field');
             var nodes  = self.zTreeObj.getCheckedNodes(true);
             var names  = '';
             var paths  = ',';
             if(1 > nodes.length) {
                 target.html('');
                 field.val('');
                 return;
             }
             for(var ele in nodes) {
                 var node = nodes[ele];
                 var path = ':' + node.id + ':';
                 var name = node.name;
                 while(true) {
                     node = node.getParentNode();
                     if(!node) {
                         break;
                     }
                     name   = $.trim(node.name) + '/' + name;
                     path   = ':' + node.id + path;
                 }
                 names      += name + ',';
                 paths      += path + ',';
             }
             $(target).html(names);
             $(field).val(paths);
             $(field + '-name').val(names);
             $('#select-address-modal').modal('hide');
         });
     },
     loadSelectAddressData: function() {
         var self   = this;
         $.getJSON(
            queryUrl + 'admin/province/alist',
            {},
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                $('#address-data-box').attr('data-loaded', 2);
                $('#address-data-box').html('<div id="ztree-address-list" class="ztree"></div>');
                self.bindZTreeData(response.data);
            }
         );
     },
     bindZTreeData: function(data) {
        var self    = this;
        var setting = {
            check: {
                enable: true 
            },
            async: {
                enable: true,
                url: queryUrl + "admin/city/alistbyztree",
                autoParam:["id", "name=n", "level=lv", 'checked=ch'],
                otherParam:{"otherParam":"zTreeAsyncTest"},
                dataFilter: function (treeId, parentNode, childNodes) {
                    if (!childNodes) { 
                        return null;
                    }
                    for (var i=0, l=childNodes.length; i<l; i++) {
                        childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
                    }
                    return childNodes;
                }
            },
            view: {
                selectedMulti: false
            },
            callback: {
                onCheck: function() {
                    //self.setParentIds();
                },
                beforeClick: function (treeId, treeNode) {
                }
            }
        };
        this.zTreeObj   = $.fn.zTree.init($('#ztree-address-list'), setting, data);
     },
    loadGoodsListAndExpList: function(val) {
        var self    = this;
        if(!val) {
            $('#parent_id').html('<option value="">先选择平台，才能选择</option>');
            $('#express_id').html('<option value="">先选择平台，才能选择</option>');
            return;
        }
        $.getJSON(
            queryUrl + 'admin/couxiao/alistexpressandgoods',
            {shop_id: val},
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                self.setGoodsOptList(response.data.goodsList);
                self.setExpressOptList(response.data.expressList);
            }
        );
    },
    bindShopIdChange: function() {
        var self    = this;
        $('#shop_id').change(function() {
            var val     = $(this).val();
            self.loadGoodsListAndExpList(val);
        });
    },
    setExpressOptList: function(list) {
        var html    = !list || 1 > list.length ? '无选项或先选择平台!' : '请选择';
        html        = '<option>' + html + '</option>';
        for(var id in list) {
            html    += '<option value="' + list[id].id + '">' + list[id].name + '</option>';
        }
        $('#express-list-tpl').html(html);
        this.setAllExpressList(html);
    },
    setGoodsOptList: function(list) {
        var html    = !list || 1 > list.length ? '无选项或先选择平台!' : '请选择';
        html        = '<option>' + html + '</option>';
        for(var id in list) {
            html    += '<option value="' + list[id].id + '">' + list[id].name + '</option>';
        }
        $('#parent_id').html(html);
        HHJsLib.autoSelect('#parent_id');
        $('#parent_id').trigger("chosen:updated");
    }
});
